package com.example.controller;

import com.example.entity.Role;
import com.example.service.RoleService;
import com.github.pagehelper.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/role")
public class RoleController {

    @Resource
    private RoleService roleService;

    // 任务二：查询角色及菜单
    @RequestMapping(value = "/withMenus", method = RequestMethod.GET)
    @ResponseBody
    public Role getRoleWithMenus(
            @RequestParam(required = false) Integer roleId,
            @RequestParam(required = false) String roleName
    ) {
        if (roleId != null) {
            return roleService.getRoleWithMenusById(roleId);
        } else if (roleName != null && !roleName.isEmpty()) {
            return roleService.getRoleWithMenusByName(roleName);
        } else {
            throw new IllegalArgumentException("Either roleId or roleName must be provided");
        }
    }

    // 任务二：分页查询角色及菜单
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getRoles(
            @RequestParam(required = false) Integer roleId,
            @RequestParam(required = false) String roleName,
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize
    ) {
        Map<String, Object> params = new HashMap<>();
        params.put("roleId", roleId);
        params.put("roleName", roleName);
        params.put("status", status);

        Page<Role> page = roleService.getRolesWithMenus(params, pageNum, pageSize);
        Map<String, Object> result = new HashMap<>();
        result.put("total", page.getTotal());
        result.put("rows", page.getResult());
        result.put("pages", page.getPages());
        return result;
    }
}